﻿using Elight.Entity.Ex;
using System;
using System.Collections.Generic;
using System.Text;

namespace Elight.Logic.Ex
{
    /// <summary>
    /// 富文本界面
    /// </summary>
    public class ExRichTextLogic : BaseLogic
    {
        /// <summary>
        /// 查询富文本
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keyWord"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<ExRichText> GetList(int pageIndex, int pageSize, string keyWord, ref int totalCount)
        {
            using (var db = GetInstance())
            { 
                totalCount = db.Queryable<ExRichText>().WhereIF(!string.IsNullOrEmpty(keyWord), it => it.Name.Contains(keyWord)).Count();
                return db.Queryable<ExRichText>().WhereIF(!string.IsNullOrEmpty(keyWord), it => it.Name.Contains(keyWord)).ToPageList(pageIndex, pageSize);
            }
        }

        /// <summary>
        /// 查询单条
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public ExRichText GetForm(string primaryKey)
        {
            using (var db = GetInstance())
            {
                return db.Queryable<ExRichText>().Where(it => it.Id == primaryKey).First();
            }
        }

        public object Insert(ExRichText model)
        {
            using (var db = GetInstance())
            {
                model.Id = Guid.NewGuid().ToString().Replace("-", "");
                return db.Insertable<ExRichText>(model).ExecuteCommand();
            }
        }

        /// <summary>
        /// 更新富文本信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(ExRichText model)
        {
            using (var db = GetInstance())
            { 
                return db.Updateable<ExRichText>(model).UpdateColumns(it => new
                {
                    it.Name,
                    it.Content
                }).ExecuteCommand();
            }
        }

        /// <summary>
        /// 删除富文本信息
        /// </summary>
        /// <param name="primaryKeys"></param>
        /// <returns></returns>
        public int Delete(params string[] primaryKeys)
        {
            using (var db = GetInstance())
            {
                try
                {
                    db.Ado.BeginTran();
                    foreach (string primaryKey in primaryKeys)
                    {
                        db.Deleteable<ExRichText>().Where(it => it.Id == primaryKey).ExecuteCommand();
                    }
                    db.Ado.CommitTran();
                    return 1;
                }
                catch (Exception ex)
                {
                    db.Ado.RollbackTran();
                    return 0;
                }
            }
        }
    }
}
